<template>
    <div>
        <el-breadcrumb>
            <el-breadcrumb-item>首页</el-breadcrumb-item>
            <el-breadcrumb-item v-breadcrumb-certify></el-breadcrumb-item>
        </el-breadcrumb>
        <div class="content release " v-show="$route.path.indexOf('/race/preview') === -1">
            <heading grade="1">发起赛事{{type}}</heading>
            <heading grade="2">赛事基本信息</heading>
            <el-form v-bind="getFormProps()" :rules="rules" ref="form" novalidate="novalidate" label-width="134px">
                <el-form-item label="运动类型：">
                    <span>{{type}}</span>
                </el-form-item>
                <el-form-item label="赛事名称："
                              prop="matchName"
                              :rules="[
               { required: true , message: '请填写赛事名称'},
               { min: 3, max: 30, message: '长度在 3 到 30 个字符',}
             ]">
                    <el-input v-model.trim="form.matchName" :minlength="3" :maxlength="30"
                              placeholder="请输入赛事名称"></el-input>
                </el-form-item>
                <el-form-item label="赛事logo："
                              prop="logoUrl"
                              :rules="[
               { required: true, message: '请上传赛事Logo'},
             ]">
                    <img-upload v-model="form.logoUrl" class="logo-upload"></img-upload>
                    <span class="form-help">(单张照片不超过5MB)</span>
                </el-form-item>
                <el-form-item label="赛事推荐图APP："
                              prop="matchImgApp"
                              :rules="[
               { required: true, message: '请上传app赛事推荐图'},
             ]">
                    <img-upload  v-model="form.matchImgApp" class="logo-upload" ></img-upload>
                    <span class="form-help">(单张照片不超过5MB)</span>
                </el-form-item>
                <el-form-item label="赛事推荐图PC："
                              prop="matchImgPc"
                              :rules="[
               { required: true, message: '请上传赛事推荐图PC'},
                  ]">
                    <img-upload v-model="form.matchImgPc" class="logo-upload"></img-upload>
                    <span class="form-help">(单张照片不超过5MB)</span>
                </el-form-item>
                <el-form-item label="所在地区："
                              prop="area"
                              :rules="[
               { required: true, message: '请选择省份'},
             ]">
                <address-cascader v-if="form.area.length" v-model="form.area" :grade="2" :label.sync="form.location"></address-cascader>
                <address-cascader v-if="!form.area.length" v-model="form.area" :grade="2" :label.sync="form.location"></address-cascader>
   
                </el-form-item>
                <el-form-item label="报名时间："
                              prop="signDate"
                              :rules="[
               { required: true, message: '请选择报名时间,报名开始的时间与报名截止的时间必须相差至少3天'},
             ]">
                    <el-date-picker
                        id="signDate"
                        v-model="signDate"
                        type="daterange"
                        placeholder="选择报名日期"
                        :picker-options="pickerOptions0"
                    >
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="比赛时间："
                              prop="matchDate"
                              :rules="[
               { required: true, message: '请选择比赛时间,比赛的开始时间须比报名的截止时间晚至少24小时'},
             ]">
                    <el-date-picker
                        id="matchDate"
                        v-model="matchDate"
                        type="daterange"
                        placeholder="选择比赛日期"
                        :picker-options="pickerOptions1"
                    >
                    </el-date-picker>
                </el-form-item>

                <heading grade="2">参赛相关信息</heading>
                <el-form-item label="竞技水平：" v-if="!isRun">
                    <el-radio-group v-model="form.sportingLevel">
                        <el-radio v-for="item in requirement[21]"
                                  :label="item.fieldValue" :key="item.fieldValue" >{{item.fieldName}}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="参赛者要求：">
                  <el-radio-group  v-model="form.joinRequire">
                      <el-radio v-for="item in requirement[20]"
                                :key="item.fieldValue" :label="item.fieldValue">{{item.fieldName}}
                      </el-radio>
                  </el-radio-group>
                </el-form-item>
                <!-- 足球篮球 且参赛者要求为球队 -->
                <el-form-item v-if="isGroupGame && (form.joinRequire==20002||form.joinRequire==20004 )" label="参赛球队数量："
                              prop="joinNumber"
                              :rules="{ required: true, type: 'number',min:4, message: '请输入参赛球队数量且大于等于4'}">
                    <el-input-number :min="4" :max="128" v-model.number="form.joinNumber" placeholder="请输入球队数量"></el-input-number>
                    <span class="form-help">(数量≥4)</span>
                </el-form-item>
                <template v-else>
                  <el-form-item v-if="form.joinRequire%2 == 1 " label="参赛者数量："
                                prop="joinNumber"
                                :rules="{ required: true, type: 'number',min:4, message: '请输入参赛者数量且大于等于4'}">
                      <el-input-number :min="4" :max="128" v-model.number="form.joinNumber" placeholder="请输入参赛者数量"></el-input-number>
                      <span class="form-help">(数量≥4)</span>
                  </el-form-item>
                  <el-form-item v-else label="参赛组合数量："
                                prop="joinNumber"
                                :rules="{ required: true, type: 'number',min:4, message: '请输入参赛组合数量且大于等于4'}">
                      <el-input-number :min="4" :max="128" v-model.number="form.joinNumber" placeholder="请输入参赛组合数量"></el-input-number>
                      <span class="form-help">(数量≥4)</span>
                  </el-form-item>
                </template>
                
                <el-form-item label="报名审核：">
                    <el-radio-group v-model="form.signChecked">
                        <el-radio v-for="item in reviewList" :key="item.value" :label="item.value">
                            {{item.label}}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="是否摇号：" v-if="isRun">
                    <el-radio-group v-model="form.lottery">
                        <el-radio v-for="item in isRoll"
                                  :key="item.value" :label="item.value">{{item.label}}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="摇号轮次：" v-if="isRun&&form.lottery==1">
                    <el-input-number placeholder="请输入摇号轮次" v-model="form.channelsRound" :min="0" :max="6"></el-input-number>
                </el-form-item>


                <el-form-item label="赛制人数：" v-if="!isRun">
                    <el-radio-group  v-model="form.formatNumberType">
                        <el-radio v-for="item in requirement[23]" :key="item.fieldName" :label="item.fieldValue">{{item.fieldName}}</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item v-if="isGroupGame&& (form.joinRequire==20002||form.joinRequire==20004 )" label="每队报名人数："
                              prop="playerNumber"
                              :rules="[
                    { required: true, message: '请输入每队报名人数'},
                      ]">
                    <el-input-number :min="3" :max="23" v-model.number="form.playerNumber" placeholder="请输入每队报名人数"></el-input-number>
                </el-form-item>

                <el-form-item label="设置组别：">
                    <el-checkbox-group v-model="form.groupTypeShow"    :min="1">
                        <el-checkbox v-for="item in requirement[22]" :label="item.fieldName" :key="item.fieldValue">{{item.fieldName}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>

                <el-form-item v-if="isRun" label="报名渠道："
                  prop="channelList"
                  :rules="[
                  { required: true, message: '请输入渠道名称'},
                  Object.assign({}, validator.rule.NumberArray,{message: '请输入渠道名额,名额为正整数'})
                  ]"
                  >                  
                  <div v-for="(item,index) in form.channelList" :key="item" class="mb10">
                    <el-row class="mb10" >
                      <el-input class="input-middle" placeholder="请输入报名渠道名称"  v-model.trim="item.channelName" :readonly="index==0"></el-input>
                      <el-button class="btn-icon" icon="minus" v-if="index>0" @click="delChannel(index)"></el-button> 
                    </el-row>
                    <el-row>
                      <el-col :span="6"  v-for="(it,$index) in item.channelsGroup" :key="it" >
                          <label>{{it.groupDes}}：</label>
                          <el-input-number :debounce="0" style="width:100px" :max="999999"  placeholder="输入名额" v-model="it.lotteryNumbers"></el-input-number>
                      </el-col>
                    </el-row>
                  </div>    
                  <el-button class="btn-icon" icon="plus" @click="addChannel()" :disabled="form.channelList.length>=6"></el-button>              
                </el-form-item>


                <el-form-item label="赛制类型："
                              prop="matchFormat"
                              :rules="[
                 { required: true, message: '请选择赛制类型'},
                ]">
                    <el-select v-model="form.matchFormat" placeholder="请选择" class="input-small">
                        <el-option
                                v-for="item in requirement[24]"
                                :key="item.fieldValue"
                                :label="item.fieldName"
                                :value="item.fieldValue">
                        </el-option>
                    </el-select>
                    <!--
                    <el-select v-if="!isGroupGame && type_en!='tennis'" v-model="form.matchFormatDish" placeholder="请选择" class="input-small">
                        <el-option
                                v-for="item in matchNumList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                    <el-select v-if="type_en=='tennis'" v-model="form.matchFormatDish" placeholder="请选择" class="input-small">
                        <el-option
                                v-for="item in tennisGameNumList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                    <el-select v-if="!isGroupGame" v-model="form.pointNum" placeholder="请选择" class="input-small">
                        <el-option
                                v-for="item in pointList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                    <el-select v-if="type_en=='tennis'" v-model="form.matchFormatPrecedence" placeholder="请选择" class="input-small">
                        <el-option
                                v-for="item in preeList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                    <span class="form-help" v-if="type_en=='badminton'">(最多可设置2个阶段)</span>
                    -->
                </el-form-item>

                <el-form-item label="是否有保险：">
                    <el-radio-group v-model="form.insuranced">
                        <el-radio v-for="item in insuranceList" :key="item.value" :label="item.value">{{item.label}}</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="报名费用：">
                  <el-radio-group v-model="form.cost">
                      <el-radio  :label="0">免费</el-radio>
                      <el-radio  :label="1">收费</el-radio>
                  </el-radio-group>
                  <div v-if="!isRun && form.cost==1">
                      <el-input-number class="input-small" v-model="form.groupMoneyList[0]" placeholder="请输入金额"></el-input-number>元
                  </div>
                  <div v-if="isRun&&form.cost==1">
                      <el-row style="margin-bottom:10px;">
                          <el-col :span="12" v-for="item in form.moneyList" :key="item">
                              <label class="run-type">{{item.fieldName}} </label>
                              <el-input-number class="input-small" placeholder="请输入费用"  v-model="item.value"></el-input-number>元
                          </el-col>
                      </el-row>
                  </div>
                </el-form-item>
                <el-form-item label="支付限时：" v-if="form.cost == 1">
                    <el-input-number v-model="form.payTime" :min="1" :max="99" class="input-small"></el-input-number>小时
                </el-form-item>

                <div v-if="isRun">                    
                    <el-form-item label="快递参赛包：">
                        <el-radio-group v-model="form.express">
                            <el-radio v-for="item in expressBag" :key="item.value" :label="item.value">
                                {{item.label}}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="衣服尺寸：">
                        <el-radio-group v-model="form.clothingSize">
                            <el-radio v-for="item in clothSize" :key="item.value" :label="item.value">{{item.label}}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="紧急联系人：">
                        <el-radio-group v-model="form.emergencyContact">
                            <el-radio v-for="item in needContactor" :key="item.value" :label="item.value">
                                {{item.label}}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                </div>

                <heading grade="2">其他信息</heading>
                <el-form-item label="联系人："
                              prop="linkMan"
                              :rules="[
               { required: true, message: '请输入联系人'},
             ]">
                    <el-input :maxlength="20" v-model.trim="form.linkMan" placeholder="请输入联系人姓名"></el-input>
                </el-form-item>
                <el-form-item label="联系方式："
                              prop="contactWay"
                              :rules="[
               { required: true, message: '请输入联系方式'},validator.rule.isPhone
             ]">
                    <el-input :maxlength="16" v-model="form.contactWay" placeholder="请输入联系方式"></el-input>
                </el-form-item>
                <el-form-item label="赛事详情："
                  prop="matchDetails"
                  :rules="[
                  { required: true, message: '请输入赛事详情'}
                  ]">
                  
                  <editor v-model="form.matchDetails" :maxlength="500" @change="$refs.form.validateField('matchDetails')"/>                 
                </el-form-item>
                <el-form-item label="主办单位"
                  prop="sponsorsList"
                  :rules="[
                  { required: true, message: '请输入主办单位名称'},
                  Object.assign({}, validator.rule.orgArray,{message: '单位名称字符应在2~30个字符'})
                ]">
                    <input-group :minlength="2" :maxlength="30" placeholder="请输入主办单位名称" :max-item="6" v-model="form.sponsorsList"></input-group>
                </el-form-item>
                <el-form-item label="承办单位"
                  prop="organizersList"
                  :rules="[
                  { required: true, message: '请输入承办单位名称'},
                  Object.assign({}, validator.rule.orgArray,{message: '单位名称字符应在2~30个字符'})
                ]">
                    <input-group :minlength="2" :maxlength="30" placeholder="请输入承办单位名称" :max-item="6" v-model="form.organizersList"></input-group>
                </el-form-item>
                <el-form-item label="协办单位" 
                 prop="corganizersList"
                 :rules="[                 
                  Object.assign({}, validator.rule.coOrgArray,{message: '单位名称字符应在2~30个字符'})
                 ]">
                    <input-group :minlength="2" :maxlength="30" placeholder="请输入协办单位名称" :max-item="6" v-model="form.corganizersList"></input-group>
                </el-form-item>
                <el-form-item label="赛事配图："
                              prop="matchImagesList"
                              :rules="[
               { required: true, message: '请上传赛事配图'},
             ]">
                    <div class="form-help">上传赛事相关图片（单张图片不超过5MB，支持jpg，png，gif格式）</div>
                    <img-group-upload v-model="form.matchImagesList" :limit="10" />
                    <div class="form-help">(最多支持上传10张,轮播的形式)</div>
                </el-form-item>
                <el-form-item label="">
                    <el-checkbox v-model="checked"><span class="small">我同意并遵守<a href="/static/protocal.html" target="_blank" class="link">《发布服务协议》</a></span>
                    </el-checkbox>
                </el-form-item>
                <div class="button-box">
                    <el-button type="primary" :disabled="!checked" @click="handleSave()"  :loading="loading&&saveLoading=='draft'">保存草稿</el-button>
                    <el-button type="primary" :disabled="!checked" @click="goPreview()">预览</el-button>
                    <el-button native-type="submit" :disabled="!checked"  :loading="loading&&saveLoading=='submit'">确认提交</el-button>
                </div>
            </el-form>

        </div>
        <!--预览赛事router-view-->
        <router-view></router-view>
    </div>
</template>

<script>
  import AddressCascader from '../components/AddressCascader'
  import InputGroup from '../components/InputGroup'
  import ImgUpload from '../components/ImgUpload'
  import ImgGroupUpload from '../components/ImgGroupUpload'
  import Editor from '../components/Editor'
  import constant from './constant'
  import raceApi from 'api/race'
  import { mapGetters } from 'vuex'
  import validator from 'utils/validator'
  import {cloneObj, dateToTimestamp, getDateDiff, addDate} from 'utils/index'
  import {form} from 'utils/mixins'
  export default {
    mixins: [form],
    components: {
      AddressCascader,
      InputGroup,
      ImgUpload,
      Editor,
      ImgGroupUpload
    },
    computed: {
      ...mapGetters({
        global: 'global',
        userId: 'userId',
        race_has_form: 'race_has_form',
        race_form: 'race_form',
        history_have: 'history_have', // 从赛事历史详情过来的
        history_race: 'history_race'
      }),
      // 是否是团队运动（足球、篮球）， (羽毛球、网球、乒乓球视为个人运动)
      isGroupGame () {
        return this.$route.params.type === 'football' || this.$route.params.type === 'basketball'
      },
      isRun () {
        return this.$route.params.type === 'run'
      },
      // 赛事类型英文
      type_en () {
        return this.$route.params.type
      },
      type () {
        return this.types[this.$route.params.type]
      },
      gameId () {
        switch (this.$route.params.type) {
          case 'football': return 3001
          case 'basketball': return 3002
          case 'badminton': return 3003
          case 'tennis': return 3004
          case 'pingpang': return 3005
          case 'run': return 3006
        }
      },
      signEndDate () {
        return this.form.signDate[1]
      },
      signDate: {
        set (value) {
          this.form.signDate = value && value[0] ? value : ''
        },
        get () {
          return this.form.signDate
        }
      },
      matchDate: {
        set (value) {
          this.form.matchDate = value && value[0] ? value : ''
        },
        get () {
          return this.form.matchDate
        }
      },
      isDouble () {
        return this.form.joinRequire
      }
    },
    mounted () {
      window.tyler5 = this
      this.getRequire()
    },
    beforeDestroy () {
      this.$store.commit('RACE_HAS_FORM', false)
      this.$store.commit('HISTORY_HAVE', false)
    },
    watch: {
      // 监听路由变化拉取参赛者要求信息
      '$route': 'getRequire',
      'isDouble': 'getMatchFormatNumberByParent'
    },
    data () {
      let self = this
      return {
        validator,
        pickerOptions0: {
          disabledDate (time) {
            return time.getTime() < Date.now() - 8.64e7
          }
        },
        pickerOptions1: {
          disabledDate (time) {
            return time.getTime() < new Date(addDate(self.signEndDate, 3)).getTime() - 8.64e7
          }
        },
        loading: false,
        saveLoading: '',
        rules: {},
        checked: false,  // 同意协议
        checkGroup: [],
        hasDraft: false, // 是否有草稿
        numberTempList: [],
        postData: {}, // 要提交的数据对象
        form: {
          id: '',
          userId: this.userId,
          matchType: this.gameId,   // 比赛类型
          matchFormat: 24001, // 赛制类型
          matchFormatDish: 3,    // 比赛盘数
          matchFormatSet: 5,  // 比赛局数
          matchFormatPoint: 11, // 赛制-分
          matchName: '',   // 赛事名称
          pointNum: null,   // 比赛每盘比分
          logoUrl: '', //
          matchImgPc: '', //
          matchImgApp: '', //
          area: [], // 省市区
          provinceId: this.provinceId,
          cityId: this.cityId,
          startTime: '',  // 比赛日期
          endTime: '',
          matchDate: '',
          signStartTime: '',
          signEndTime: '',
          signDate: '',     // 报名日期
          sportingLevel: 21015,   // 竞技水平
          joinRequire: 20001,    // 参赛者要求
          lottery: 0,       // 是否摇号
          channelsRound: 1,     // 摇号轮次
          channelList: [
            {
              channelName: '求苗',
              channelsGroup: []
            }
          ],
          matchChannelsList: [], // 渠道列表
          joinNumber: 4,      // 参赛球队数量
          matchFormatPrecedence: 1,   // 是否有占先
          signChecked: 1,        // 报名是否需要审核
          formatNumberType: 23001,     // 赛制人数
          playerNumber: 1,   // 每队报名人数
          groupTypeList: [],  // 组别
          groupTypeShow: [],  // 组别文本
          insuranced: 1,    // 是否有保险
          cost: 1,         // 收费或免费
          groupMoneyList: [], // 球类收费
          moneyList: [],
          groupTypeMoneyList: [],  // 跑步收费
          express: 1, // 快递参赛包
          clothingSize: 1, // 衣服尺寸
          emergencyContact: 1, // 是否需要紧急联系人
          payTime: 1,  // 支付限时
          linkMan: '', // 联系人
          contactWay: '',  // 联系方式
          remarks: '',  // 备注
          matchDetails: '', // 赛事详情
          sponsorsList: [], // 主办单位
          organizersList: [], // 承办单位
          corganizersList: [], // 协办单位
          matchImagesList: [],
          status: 0,
          drawsState: 0 // 签表状态 0：未生成，1：草稿：2已生成,3已创建赛程
        },
        requirement: {},
        ...constant
      }
    },
    methods: {
      getDraft () { // 获取草稿
        if (this.race_has_form) { // vuex中保存有赛事
          this.form = this.race_form
          this.form.channelList = cloneObj(this.race_form.matchChannelsList)
          return
        }
        raceApi.getDraft({matchType: this.gameId}, this).then((res) => {
          if (res.data) { // 有草稿
            this.hasDraft = true
            var rdata = res.data
            this.form.matchName = rdata.matchName
            this.form.matchType = rdata.matchType
            if (rdata.logoUrl.length) {
              this.form.logoUrl = rdata.logoUrl
            }
            if (rdata.matchImgPc.length) {
              this.form.matchImgPc = rdata.matchImgPc
            }
            if (rdata.matchImgApp.length) {
              this.form.matchImgApp = rdata.matchImgApp
            }
            this.form.joinRequire = rdata.joinRequire
            this.form.provinceId = rdata.provinceId
            this.form.cityId = rdata.cityId
            this.form.area[0] = rdata.provinceId
            this.form.area[1] = rdata.cityId
            this.form.matchImagesList = []
            if (rdata.matchImagesList.length) {
              this.form.matchImagesList = rdata.matchImagesList
            }
            if (rdata.signStartTime) { // 设置报名时间
              this.signDate = [new Date(rdata.signStartTime), new Date(rdata.signEndTime)]
            }
            if (rdata.startTime) { // 设置比赛时间
              this.matchDate = [new Date(rdata.startTime), new Date(rdata.endTime)]
            }
            // 参赛相关信息
            this.form.sportingLevel = rdata.sportingLevel
            this.form.joinRequire = rdata.joinRequire
            this.form.joinNumber = rdata.joinNumber
            this.form.signChecked = rdata.signChecked
            this.form.formatNumberType = rdata.formatNumberType
            this.form.playerNumber = rdata.playerNumber
            this.form.payTime = rdata.payTime
            if (this.isRun) { // 跑步
              if (rdata.groupTypeList && rdata.groupTypeList.length) { // 设置渠道报名费用的label
                this.form.groupTypeShow = []
                if (this.requirement && this.requirement[22].length) {
                  for (var i = 0, len = this.requirement[22].length; i < len; i++) { // eslint-disable-line
                    for (var j = 0, jlen = rdata.groupTypeList.length; j < jlen; j++) { // eslint-disable-line
                      if (this.requirement[22][i].fieldValue == rdata.groupTypeList[j].groupType) { // eslint-disable-line
                        this.form.groupTypeShow[i] = this.requirement[22][i].fieldName
                      }
                    }
                  }
                }
              }
              if (rdata.matchChannelsList && rdata.matchChannelsList.length) { // 设置渠道信息
                this.form.channelList = []
                rdata.matchChannelsList.forEach(item => {
                  for (var i = 0, len = item.channelsGroup.length; i < len; i++) { // eslint-disable-line
                    for (var j = 0 , jlen = this.requirement[22].length; j < jlen; j++) { // eslint-disable-line
                      if (item.channelsGroup[i].groupType == this.requirement[22][j].fieldValue) // eslint-disable-line
                        item.channelsGroup[i].groupDes = this.requirement[22][j].fieldName
                    }
                  }
                })
                this.form.channelList = rdata.matchChannelsList
              }
              if (rdata.groupTypeList && rdata.groupTypeList.length) { // 报名费用
                for (let n = 0, nlen = this.requirement[22].length; n < nlen; n++) {
                  this.form.moneyList[n].value = rdata.groupTypeList[n] ? rdata.groupTypeList[n].groupMoney : 0
                }
              }
            } else { // 球类
              if (rdata.groupTypeList && rdata.groupTypeList.length) {
                for (var i = 0, len = this.requirement[22].length; i < len; i++) { // eslint-disable-line
                  for (var j = 0, jlen = rdata.groupTypeList.length; j < jlen; j++) { // eslint-disable-line
                    if (this.requirement[22][i].fieldValue == rdata.groupTypeList[j].groupType) { // eslint-disable-line
                      this.form.groupTypeShow[i] = this.requirement[22][i].fieldName
                    }
                  }
                }
              }
              this.form.groupMoneyList[0] = rdata.groupTypeList ? rdata.groupTypeList[0].groupMoney : 0
            }
            this.form.matchFormat = rdata.matchFormat
            this.form.insuranced = rdata.insuranced
            this.form.cost = rdata.cost
            this.form.linkMan = rdata.linkMan
            this.form.contactWay = rdata.contactWay
            this.form.matchDetails = rdata.matchDetails
            if (rdata.sponsorsList.length) {
              this.form.sponsorsList = rdata.sponsorsList
            }
            if (rdata.organizersList.length) {
              this.form.organizersList = rdata.organizersList
            }
            if (rdata.corganizersList.length) {
              this.form.corganizersList = rdata.corganizersList
            }
          }
        })
      },
      setHistoryInfo () {
        var f = this.form
        var h = this.history_race
        f.matchName = h.matchName
        f.logoUrl = h.logoUrl
        f.matchImgPc = h.matchImgPc
        f.matchImgApp = h.matchImgApp
        f.area[0] = h.provinceId
        f.area[1] = h.cityId
        f.sportingLevel = h.sportingLevel
        f.joinRequire = h.joinRequire
        f.joinNumber = h.joinNumber
        f.signChecked = h.signChecked
        f.formatNumberType = h.formatNumberType
        f.matchImagesList = h.matchImagesList
        f.matchFormat = h.matchFormat
        f.drawsState = h.drawsState
        f.insuranced = h.insuranced
        f.cost = h.cost
        f.lottery = h.lottery
        if (h.matchType !== 3006) {
          h.groupTypeList && h.groupTypeList.forEach(item => {
            f.groupTypeShow.push(item.groupTypeStr)
          })
        } else {
          var gtList = h.groupTypeList
          f.groupTypeShow = []
          for (var i = 0, l = gtList.length; i < l; i++) {
            f.groupTypeShow.push(gtList[i].groupTypeStr)
            for (var j = 0, jl = f.moneyList.length; j < jl; j++) {
              if (f.moneyList[j].fieldName === gtList[i].groupTypeStr) {
                f.moneyList[j].value = gtList[i].groupMoney
              }
            }
          }
        }
        if (h.matchChannelsList && h.matchChannelsList.length) {
          f.channelList = h.matchChannelsList
        }
        f.groupMoneyList[0] = h.groupTypeList && h.groupTypeList.length && h.groupTypeList[0].groupMoney
        f.payTime = h.payTime
        f.express = h.express || 1
        f.clothingSize = h.clothingSize || 1
        f.emergencyContact = h.emergencyContact || 1
        f.linkMan = h.linkMan
        f.contactWay = h.contactWay
        f.matchDetails = h.matchDetails
        f.sponsorsList = Array.isArray(h.sponsorsList) ? h.sponsorsList : []
        f.organizersList = Array.isArray(h.organizersList) ? h.organizersList : []
        f.corganizersList = h.corganizersList ? (Array.isArray(h.corganizersList) ? h.corganizersList : []) : []
      },
      getMatchFormatNumberByParent () {
        if (!this.isGroupGame && !this.isRun) { // 羽毛球，网球，乒乓球
          raceApi.getMatchFormatNumberByParent({parentValue: this.form.joinRequire}, this).then((res) => {
            this.requirement[23] = res.data
          })
        }
      },
      // 获取参赛相关信息
      getRequire () {
        if (this.$route.name === 'preview') {
          return
        }
        if (this.isRun) { // 跑步
          raceApi.runRequirement({matchType: this.gameId}, this).then((res) => {
            let json = JSON.stringify(res.data[22])
            this.requirement = res.data
            this.form.moneyList = JSON.parse(json) // 深拷贝
            this.numberTempList = []
            res.data[22].forEach(i => {
              this.numberTempList.push({
                groupDes: i.fieldName,
                lotteryNumbers: 0
              })
            })
            this.form.channelList[0].channelsGroup = JSON.parse(JSON.stringify(this.numberTempList))
            this.form.moneyList.forEach(function (j) {
              j.value = ''
            })
            this.setRadio()
            if (this.history_have) {
              this.setHistoryInfo()
            } else {
              this.getDraft()
            }
          })
        } else { // 球类
          raceApi.requirement({matchType: this.gameId}, this).then((res) => {
            this.requirement = res.data
            this.checkGroup = this.requirement[22]
            this.groupTypeMoneyList = ['']
            this.setRadio()
            if (this.history_have) {
              this.setHistoryInfo()
            } else {
              this.getDraft()
            }
          })
        }
      },
      setRadio () { // 设置单选框选项
        if (this.requirement[21] && this.requirement[21].length) {
          this.form.sportingLevel = this.requirement[21][0].fieldValue // 竞技水平
        }
        if (this.requirement[22] && this.requirement[22].length) {
          this.form.groupTypeShow = []
          this.form.groupTypeShow.push(this.requirement[22][0].fieldName)
        }
        if (this.requirement[23] && this.requirement[23].length) {
          this.form.formatNumberType = this.requirement[23][0].fieldValue // 赛制人数
        }
        this.form.joinRequire = this.requirement[20][0].fieldValue // 参赛者要求
        this.form.matchFormat = this.requirement[24][0].fieldValue // 赛制类型
      },
      // 手动验证
      customValid () {
        this.formatData()
        let message
        let isSuccess = true
        let d = new Date()
        if (!this.form.location) {
          message = '请选择所在地区'
          isSuccess = false
        }
        if (dateToTimestamp(this.form.signStartTime) < dateToTimestamp(d) - 86400000) {
          message = '报名时间不能小于当前时间'
          isSuccess = false
        }
        if (dateToTimestamp(this.form.startTime) < dateToTimestamp(d)) {
          message = '比赛时间不能小于当前时间'
          isSuccess = false
        }
        if (getDateDiff(this.form.signEndTime, this.form.signStartTime) < 3) {
          message = '报名结束日期必须比报名开始日期晚3天'
          isSuccess = false
        }
        if (getDateDiff(this.form.startTime, this.form.signEndTime) < 2) {
          message = '比赛开始日期必须比报名结束日期晚2天'
          isSuccess = false
        }
        if (this.form.matchImagesList.length > 10) {
          message = '最多上传10张赛事配图'
          isSuccess = false
        }
        if (this.form.cost && (this.gameId !== 3006) && this.form.groupMoneyList[0] <= 0) {
          message = '报名费用需大于0'
          isSuccess = false
        }
        if (this.form.cost && this.gameId === 3006) {
          for (var i = 0, len = this.form.moneyList.length; i < len; i++) {
            if ((this.form.groupTypeShow.indexOf(this.form.moneyList[i].fieldName) > -1) && this.form.moneyList[i].value <= 0) {
              message = '报名费用需大于0'
              isSuccess = false
              break
            }
          }
        }
        if (!isSuccess) {
          return {
            isSuccess: false,
            errMsg: message
          }
        } else {
          return {
            isSuccess: true
          }
        }
      },
      handleSuccess (isSubmit) {
        if (isSubmit) {
          const h = this.$createElement
          this.$msgbox({
            title: '温馨提示',
            message: h('div', {'class': {
              msgBody: true,
              clearfix: true
            }}, [
              h('div', {
                'class': {
                  success: true
                }
              }, ''),
              h('div', {
                'class': {
                  showtip: true
                }
              }, [
                h('p', {
                  'class': {
                    successTitle: true
                  }
                }, '赛事申请成功'),
                h('p', null, '我们将会在2个工作日内完成审核工作，请耐心等待！')
              ])
            ]),
            showCancelButton: false,
            confirmButtonText: '确定',
            callback: action => {
              this.$router.push({path: '/race/release'})
            }
          })
        } else {
          this.$message('提交成功')
          this.$router.push({path: '/race/release'})
        }
      },
      // 格式化提交数据
      formatData () {
        this.postData = cloneObj(this.form)
        var form = this.form
        if (!form.matchType) {
          form.matchType = this.gameId
        }
        form.userId = this.userId
        form.provinceId = form.area[0] || ''
        form.cityId = form.area[1] || ''
        form.payTime = form.payTime > 1 ? parseInt(form.payTime) : form.payTime
        if (form.matchDate.length) {
          form.startTime = new Date(form.matchDate[0]).format()
          form.endTime = new Date(form.matchDate[1]).format()
        }
        if (form.signDate.length) {
          form.signStartTime = new Date(form.signDate[0]).format()
          form.signEndTime = new Date(form.signDate[1]).format()
        }
        if (!this.isRun) {
          form.groupTypeList = []
          let money = form.groupMoneyList[0]
          form.groupMoneyList = []
          form.groupTypeShow.forEach(item1 => {
            this.requirement[22].forEach(item2 => {
              if (item1 == item2.fieldName) { // eslint-disable-line
                form.groupTypeList.push(item2.fieldValue)
                form.groupMoneyList.push(money)
              }
            })
          })
        }
      },
      formatRunData () {
        var form = this.form
        form.groupTypeMoneyList = []
        form.matchChannelsList = []
        form.moneyList.forEach(item => { // 报名费用
          if (form.groupTypeShow.indexOf(item.fieldName) > -1) {
            form.groupTypeMoneyList.push(item.value)
          }
        })
        var result = []
        this.requirement[22].forEach(item => { // 输入选中的组别
          if (form.groupTypeShow.indexOf(item.fieldName) > -1) {
            result.push(item.fieldValue)
          }
        })
        form.groupTypeList = result
        var groupLength = this.requirement[22].length
        for (var i = 0, len = form.channelList.length; i < len; i++) {
          form.matchChannelsList.push({
            channelName: form.channelList[i].channelName,
            channelsGroup: [
              {groupType: this.requirement[22][0].fieldValue, groupDes: this.requirement[22][0].fieldName, lotteryNumbers: 0},
              {groupType: this.requirement[22][1].fieldValue, groupDes: this.requirement[22][1].fieldName, lotteryNumbers: 0},
              {groupType: this.requirement[22][2].fieldValue, groupDes: this.requirement[22][2].fieldName, lotteryNumbers: 0},
              {groupType: this.requirement[22][3].fieldValue, groupDes: this.requirement[22][3].fieldName, lotteryNumbers: 0}
            ]
          })
          for (var j = 0; j < groupLength; j++) {
            form.matchChannelsList[i].channelsGroup[j].lotteryNumbers = form.channelList[i].channelsGroup[j].lotteryNumbers
          }
        }
      },
      timeFormat () {
        this.form.startTime = this.form.startTime.length ? dateToTimestamp(this.form.startTime) : ''
        this.form.endTime = this.form.endTime.length ? dateToTimestamp(this.form.endTime) : ''
        this.form.signStartTime = this.form.signStartTime.length ? dateToTimestamp(this.form.signStartTime) : ''
        this.form.signEndTime = this.form.signEndTime.length ? dateToTimestamp(this.form.signEndTime) : ''
      },
      submit () {
        var custValid = this.customValid()
        if (!custValid.isSuccess) {
          this.$message({
            message: custValid.errMsg,
            type: 'warning'
          })
          return false
        }
        this.saveLoading = 'submit'
        this.$confirm('确定要提交比赛吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.timeFormat()
          var formData
          if (this.isRun) {
            this.formatRunData()
            formData = cloneObj(this.form)
            raceApi.releaseRun(formData, {context: this}).then((res) => {
              this.handleSuccess(true)
              this.$store.commit('RACE_HAS_FORM', false)
            })
          } else {
            formData = cloneObj(this.form)
            raceApi.release(formData, {context: this}).then((res) => {
              this.handleSuccess(true)
            }).catch((err) => {
              this.$message({
                message: err.msg,
                type: 'warning'
              })
            })
            this.$store.commit('RACE_HAS_FORM', false)
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      },
      // 预览
      goPreview (formName) {
        this.validate(() => {
          var custValid = this.customValid()
          if (!custValid.isSuccess) {
            this.$message({
              message: custValid.errMsg,
              type: 'warning'
            })
            return false
          }
          let data = {
            cost: this.form.cost,
            isPreview: true,
            logoUrl: this.form.logoUrl,
            matchName: this.form.matchName,
            matchType: this.gameId || this.form.matchType,
            status: 1,
            matchTypeStr: this.type,
            startTime: this.form.matchDate[0],
            endTime: this.form.matchDate[1],
            signStartTime: this.form.signDate[0],
            signEndTime: this.form.signDate[1],
            provinceStr: this.form.location[0],
            cityStr: this.form.location[1],
            groupMoney: this.form.cost ? this.form.groupMoneyList[0] : '免费',
            sportingLevelStr: '',
            joinNumber: this.form.joinNumber,
            joinRequireStr: this.requirement[20].filter(item => {
              return item.fieldValue === this.form.joinRequire
            }),
            playerNumber: this.form.playerNumber + '人',
            matchFormatStr: this.requirement[24].filter(item => {
              return item.fieldValue === this.form.matchFormat
            }),
            linkMan: this.form.linkMan,
            contactWay: this.form.contactWay,
            sponsorsList: this.form.sponsorsList,
            organizersList: this.form.organizersList,
            corganizersList: this.form.corganizersList,
            remarks: this.form.remarks,
            matchDetails: this.form.matchDetails,
            matchImagesList: this.form.matchImagesList,
            formatNumberTypeStr: '',
            groupTypeList: [],
            groupTypeMoneyList: [],
            matchChannelsList: [],
            channelsRound: this.form.channelsRound
          }
          if (this.gameId !== 3006) {
            this.requirement[23].forEach(item => {
              if(item.fieldValue == this.form.formatNumberType) { // eslint-disable-line
                data.formatNumberTypeStr = item.fieldName
              }
            })
            this.requirement[21].forEach(item => {
              if(item.fieldValue == this.form.sportingLevel){ // eslint-disable-line
                data.sportingLevelStr = item.fieldName
              }
            })
          }
          if (this.gameId === 3006) { // 跑步
            var moneyList = []
            this.form.moneyList.forEach(item => {
              if (this.form.groupTypeShow.indexOf(item.fieldName) > -1) {
                moneyList.push(item.value)
              }
            })
            data.groupTypeList = this.form.groupTypeShow
            data.groupTypeMoneyList = moneyList
            data.matchChannelsList = cloneObj(this.form.channelList)
            this.formatRunData()
          }
          this.$store.commit('RACE_PREVIEW', Object.assign({}, data, { // 调用mutation改变数据
            type: this.$route.params.type
          }))
          this.timeFormat()
          this.$store.commit('RACE_FORM', Object.assign({}, this.form))
          this.$store.commit('RACE_HAS_FORM', true)
          this.$router.push({name: 'preview'})
        })
      },
      // 保存草稿
      handleSave () {
        this.formatData()
        this.timeFormat()
        if (this.isRun) {
          this.formatRunData()
        }
        this.saveLoading = 'draft'
        this.$store.commit('RACE_HAS_FORM', false)
        raceApi.draft(this.form, {context: this}).then((res) => {
          this.handleSuccess()
        }).catch((err) => {
          this.$message({
            message: err.msg,
            type: 'warning'
          })
        })
      },
      // 添加渠道
      addChannel () {
        if (this.form.channelList.length >= 6) {
          return
        }
        this.form.channelList.push({
          channelName: '',
          channelsGroup: JSON.parse(JSON.stringify(this.numberTempList))
        })
      },
      delChannel (index) {
        this.form.channelList.splice(index, 1)
      }
    }
  }
</script>

<style lang="scss" scoped>
  .logo-upload {
      width: 160px;
      height: 90px;
  }
  .run-type {
      width: 50px;
      text-align: right;
      display: inline-block;
  }
  .mb10{
    margin-bottom:10px;
  }
  .disabled {
    cursor: not-allowed
  }
  .success{
    background-image: url('/static/images/login/right.png');
    background-size: contain;
    width: 49px; 
    height: 50px;
    display: inline-block;
    margin-right:20px;
    float: left;
  }
  .showtip{
    display: inline-block;
    float: left;
    width:180px;
    text-align: left;
    p{
      font-size: 12px;
      color:#666;
    }
    .successTitle{
      font-size: 18px;
      color:#00bb90;
      margin-bottom: 15px;
    }
  }
  .msgBody{
    width:250px;
    margin: 0 auto;
  }
</style>
